<?php
/*

  Copyright (c) 2008   by  maxim.oransky <maxim.oransky@gmail.com>,
  auhtor of  the-wheel-library  team

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

class HtmlFormatter {

	public static function formatPAndBr($str) {

		$hRules = array(
			'~\n(\s+)?\n~m'   => "\n\n",
			'~\n~' 			  => '<br>',
			'~<br>\s*<br>~'   => '<p>',
			'~<p>\s*<p>~'     => '<p>',
			'~<(p|br)>(<(h[12345]|ul|li|ol)[^>]*>)~s' => '$2',
		);

		$str = preg_replace(array_keys($hRules), array_values($hRules),$str);
		$str = '<p>' . $str . '</p>';

		$str = strtr($str, array(
			'<br></p>' => '</p>',
		));

		return $str;
	}

	public static function formatP($str) {

	    $str = "\n\n" . trim($str);

		$newLine = '(?:\r?\n)';
		$str = preg_replace("~($newLine{2,})([^\r\n]{2,})~U", "\n\n<p>\$2", $str);
		$str = preg_replace("~($newLine{2,})<p>~U",	"</p>\n\n<p>", $str);
		$str = preg_replace('~^\s*</p>~s', '', $str);

		$str = $str . '</p>';

		return $str;
	}

	public static function formatBR($str) {
		return preg_replace('/(\r?\n)/', "<br />\n", $str);
	}

	public static function removeHtml($str) {
		return strip_tags($str);
	}

	public static function removeNewlines($str) {
	//	return preg_replace('/(\r|\n)/', ' ', $str);
		return strtr($str, array("\r" => "", "\n" => ""));
	}

	public static function markLinks($str) {
		return preg_replace_callback(
		    "~\b(?:https?://|www\.)(?:\S*)~",
			create_function('$m', 'return "<a href=\"$m[0]\">" . urldecode($m[0]) . "</a>";'),
			$str
		);
	}
}

?>
